package com.qjq.glasses_shopping.controller;


import com.qjq.glasses_shopping.pojo.CartGoods;
import com.qjq.glasses_shopping.result.BaseResult;
import com.qjq.glasses_shopping.service.CartService;
import com.qjq.glasses_shopping.util.JwtUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user/cart")
public class CartController {
    @Resource
    private CartService cartService;

    /**
     * 获取购物车列表
     * @param authorization 解析token获取用户id
     * @return 购物车列表
     */
    @GetMapping("/findCartList")
    public BaseResult<List<CartGoods>> findCartList(@RequestHeader("Authorization") String authorization) {
        String token = authorization.replace("Bearer ","");
        Map<String, Object> verify = JwtUtils.verify(token);
        Long userId = (Long) verify.get("userId");
        List<CartGoods> cartList = cartService.findCartList(userId);
        return BaseResult.ok(cartList);
    }

    /**
     * 新增商品到购物车
     * @param cartGoods 购物车商品
     * @RequestHeader(value = "Authorization",defaultValue = "token") String authorization
     * @return 操作结果
     */
    @PostMapping("/addCart")
    public BaseResult addCart(@RequestBody CartGoods cartGoods, HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
            if (authorization == null || authorization.isEmpty()){
                return BaseResult.ok("token");
            }
        String token = authorization.replace("Bearer ","");
        Map<String, Object> verify = JwtUtils.verify(token);
        Long userId = (Long) verify.get("userId");
        cartService.addCart(userId,cartGoods);
        return BaseResult.ok();
    }

    /**
     * 修改购物车商品数量
     * @param authorization 令牌中携带的用户Id
     * @param goodId 商品id
     * @param num 修改后的数量
     * @return 操作结果
     */
    @GetMapping("/handleCart")
    public BaseResult addCart(@RequestHeader("Authorization") String authorization,Long goodId,Integer num){
        String token = authorization.replace("Bearer ","");
        Map<String, Object> verify = JwtUtils.verify(token);
        Long userId = (Long) verify.get("userId");
        cartService.handleCart(userId,goodId,num);
        return BaseResult.ok();
    }

    /**
     * 删除购物车商品
     * @param authorization 令牌中
     * @param goodId 商品id
     * @return 操作结果
     */
    @DeleteMapping("/deleteCart")
    public BaseResult deleteCart(@RequestHeader("Authorization") String authorization,Long goodId){
        String token = authorization.replace("Bearer ","");
        Map<String, Object> verify = JwtUtils.verify(token);
        Long userId = (Long) verify.get("userId");
        cartService.deleteCartOption(userId,goodId);
        return BaseResult.ok();
    }

}
